<template>
  <div>
    <!-- 内容主体区域 -->
    <dtDialog title="修改数据范围" :visible.sync="visible" :is-loading="loading" @closeDialog="handleClose()" @comfirmBtn="onSubmit()">
      <el-form ref="form" slot="content" :model="formData" label-width="72px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" autocomplete="off" placeholder="请输入角色名称" disabled />
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScopeType">
          <el-radio-group v-model="formData.dataScopeType" @change="changeHandler">
            <el-radio :label="10">仅本人数据</el-radio>
            <el-radio :label="20">本部门数据</el-radio>
            <el-radio :label="30">本部门及以下数据</el-radio>
            <el-radio :label="40">指定部门数据</el-radio>
            <el-radio :label="50">全部数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-tree
            v-if="formData.dataScopeType == 40"
            ref="tree"
            class="tree"
            :data="formData.tree"
            :props="defaultProps"
            show-checkbox
            :load="load"
            lazy
            node-key="id"
            :default-checked-keys="checkedKeys"
            :default-expand-all="false"
            :check-on-click-node="true"
            :expand-on-click-node="false"
            :check-strictly="true"
            @check="handleNodeCheck"
          />
        </el-row>
      </el-form>
    </dtDialog>
  </div>
</template>
<script>
import api from '@/framework/api/role'
import roleApi from '@/framework/api/role'
export default {
  name: 'RoleDataScope',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    closeForm: {
      type: Function,
      default: function() {}
    }
  },
  data() {
    return {
      loading: false,
      grantOrgIdList: [],
      checkedKeys: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'name'
      },
      nodeTree: {}
    }
  },
  methods: {
    // 获取数据范围列表
    getRoleBindOrgScope(data, detailData) {
      const list = []
      this.checkedKeys = detailData.dataScopeOrganizationIds
      this.grantOrgIdList = this.checkedKeys
    },
    isChecked(data, list) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length > 0) {
          this.isChecked(data[i].children, list)
        } else {
          if (data[i].checked) {
            list.push({
              'id': data[i].id,
              'label': data[i].name
            })
          }
        }
      }
    },
    async handleNodeCheck(data) {
      const list = []
      const orgList = this.$refs.tree.getCheckedNodes()
      for (let i = 0; i < orgList.length; i++) {
        list.push(orgList[i].id)
      }
      this.grantOrgIdList = list

      // const CurrentKey = this.$refs.tree.getCurrentKey()
      // this.refreshNode(this.$refs.tree.getCurrentKey())
      const node = this.$refs.tree.getNode(data)
      if (node.checked || node.data.disabled) { // 判断是否禁用子节点--禁用
        await this.$nextTick()
        this.dealTreeData(node, !node.data.disabled)
      } else {
        this.dealTreeData(node, false)
      }
    },
    // 刷新某个树节点，重点！！！！
    refreshNode(key) {
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      const node = this.$refs.tree.getNode(key)
      //  设置未进行懒加载状态
      node.loaded = false
      // 重新展开节点就会间接重新触发load达到刷新效果
      node.expand()
    },
    // 关闭对话框触发
    handleClose() {
      // 清空数据关闭页面
      this.$refs['form'].resetFields()
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedNodes([])
      })
      this.closeForm()
    },
    async onSubmit() {
      this.loading = true
      if (this.formData.dataScopeType === 40 && (!this.grantOrgIdList || (this.grantOrgIdList && this.grantOrgIdList.length === 0))) {
        this.$message({
          type: 'error',
          message: '请选择部门'
        })
        this.loading = false
        return false
      }
      const data = {
        'dataScopeType': this.formData.dataScopeType,
        'grantOrgIdList': this.grantOrgIdList,
        'roleId': this.formData.roleId
      }
      try {
        const res = await api.grantDataScope(data)
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.handleClose()
        } else {
          this.$message({
            type: 'error',
            message: '修改失败'
          })
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    changeHandler(value) {
      // if (value === "40") {
      //   this.getRoleBindOrgScope()
      // }
    },
    load(tree, resolve) {
      let id = ''
      if (!tree.data || tree.data.length == 0) {
        id = 0
      } else if (tree.data.length > 0) {
        resolve(tree.data)
        return
      } else {
        id = tree.data.id
      }
      roleApi.roleBindOrgScopeLazyAntdv({ roleId: this.formData.roleId, orgId: id }).then((res) => {
        resolve(res.data)
      })
      // this.nodeTree = tree
      if (tree.checked || tree.data.disabled) { // 判断是否禁用子节点
        this.$nextTick()
        this.dealTreeData(tree, true)
      }
    },

    /**
     * 节点状态改变
     */
    handleCheckClick(node, checked) {
      this.dealSelectAllChildrenTreeData(node, checked)
      // const a = this.$refs.tree.getNode(node)
      this.deepCheck(this.$refs.tree.getNode(node)) // 深拷贝处理权限 未完成功能 只处理了全选 未实现反显 功能暂时搁置
      this.currentIdList = this.$refs.tree.getCheckedKeys()
    },
    deepCheck(treeNode) {
      if (treeNode.childNodes && treeNode.childNodes.length > 0) {
        treeNode.childNodes.forEach(element => {
          element.checked = true
          this.deepCheck(element)
        })
      }
    },
    dealSelectAllChildrenTreeData(node, checked) {
      // 全部取消/选择
      const setChecked = (arr, ifChecked) => {
          arr?.map((item) => {
            this.$refs.tree.setChecked(item.id, ifChecked)
            if (item?.children?.length) {
              setChecked(item?.children, ifChecked)
            }
          })
      }
      // 如果为取消
      if (checked === false) {
        // 如果当前节点有子集
        // 循环子集将他们的选中取消
        setChecked(node?.children ?? [], false)
      } else {
        // 否则(为选中状态)
        // 判断父节点id是否为空
        if (node.parentId !== 'all') {
          // 如果不为空则将其选中
          // 循环子集将他们的选中取消
          setChecked(node?.children ?? [], true)
        }
      }
    },
    // 节点点击回调
    async  handleNodeClick(data, node, com) {
      if (node.checked || node.data.disabled) { // 判断是否禁用子节点--禁用
        await this.$nextTick()
        this.dealTreeData(node, !node.data.disabled)
      } else {
        this.dealTreeData(node, false)
      }
    },

    // 递归处理treeData
    dealTreeData(node, status) {
      setTimeout(() => {
        node.childNodes.forEach(res => {
          this.setDisabledTreeData(node.childNodes, res.id, status)
          if (res.childNodes && res.childNodes.length > 0) {
            this.dealTreeData(res, status)
          }
        })
      }, 200)
    },
    /**
     * 禁用节点
     * @param {*} data
     * @param {*} id 值不为undefined设置禁用节点；反之则清除禁用节点
     * @param {*} status true 禁用  false 不禁用
     */
    setDisabledTreeData(data, id, status) {
      // const val = id !== undefined
      data.forEach((item) => { // 遍历整个树 数据
        this.$set(item.data, 'disabled', status)
        status && this.$refs.tree.setChecked(item, false)

        // if (id == undefined || item.id == id) { // 如果有id相等 则禁用
        //   this.$set(item, 'disabled', true)
        //   if (status) {
        //     // 禁用后 所有子节点全部取消勾选
        //     this.$refs.tree.setCheckedKeys(this.$refs.tree.getCheckedKeys().filter(num => {
        //       return num != item.id
        //     }))
        //   }
        //   return
        // }
      })
    }
  }
}
</script>

<style scoped>

</style>
